package com.book.controller;

import com.book.entity.BookEntity;
import com.book.entity.CartEntity;
import com.book.service.CartService;
import com.book.utils.JwtUtils;
import com.book.utils.TransitionUtils;
import com.book.utils.R;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.midi.Soundbank;
import java.util.List;

@RestController
@RequestMapping("/book/info")
public class CartController {

    @Resource
    private CartService cartService;

    @PostMapping("/save/cart/{userId}")
    public R addCart(@PathVariable("userId")Long userId, @RequestBody BookEntity bookEntity, HttpServletRequest request) throws JsonProcessingException {
        CartEntity cart = cartService.addCart(bookEntity, userId);
        List<BookEntity> bookEntities = TransitionUtils.mapTransitionArray(cart.getBooks());
        if(JwtUtils.checkToken(request)){
            return R.ok().put("cart",cart).put("books",bookEntities);
        }else{
            return R.error("token不合法");
        }

    }


    @GetMapping("/get/cart/{userId}")
    public R getCart(@PathVariable("userId")Long userId){
        CartEntity cart = cartService.getCart(userId);
        List<BookEntity> bookEntities = null;
        if(cart != null) {
             bookEntities = TransitionUtils.mapTransitionArray(cart.getBooks());
        }
        return R.ok().put("cart",cart).put("books",bookEntities).put("bookJson",TransitionUtils.objectTransitionArray(bookEntities));
    }

    @PostMapping("/delete/cart/{userId}/{bookId}")
    public R deleteCart(@PathVariable("userId")Long userId,@PathVariable("bookId") Long bookId){
        CartEntity cart = cartService.deleteCart(userId, bookId);
        List<BookEntity> bookEntities = TransitionUtils.mapTransitionArray(cart.getBooks());
        return R.ok().put("cart",cart).put("books",bookEntities);
    }

    @PostMapping("/clear/cart/{userId}")
    public R clearCart(@PathVariable("userId")Long userId){
        cartService.clearCart(userId);
        CartEntity cart = cartService.getCart(userId);
        return R.ok().put("cart",cart);
    }


    @PostMapping("/update/cart/{userId}/{bookId}/{count}")
    public R updateCart(@PathVariable("userId")Long userId,@PathVariable("bookId")Long bookId,@PathVariable("count")Integer count){
        CartEntity cart= cartService.updateCart(bookId, count, userId);
        List<BookEntity> bookEntities = TransitionUtils.mapTransitionArray(cart.getBooks());
        return R.ok().put("cart",cart).put("books",bookEntities);
    }

}
